package com.kaching.twitter.cron


import java.io.IOException
import javax.servlet.http._
import scala.collection.jcl.Conversions._
import _root_.twitter4j._
import _root_.com.kaching.twitter.PMF
import _root_.com.kaching.twitter.stats.DirectMessages
import javax.jdo.PersistenceManager
import _root_.com.google.appengine.api.datastore.Key
import _root_.com.google.appengine.api.datastore.KeyFactory
import _root_.javax.jdo.JDOObjectNotFoundException
import scala.util.matching.Regex

class FetchDmServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest,  resp: HttpServletResponse) : Unit = {
    println("working on DM")
    val pm : PersistenceManager = PMF.get.getPersistenceManager
    try{
      val dms = getDirectMessages(pm)
      val twitter = new Twitter(TwitterCredentials.userName, TwitterCredentials.password)
      val tweets = dms match {
        case null => twitter.getDirectMessages
        case _ => twitter.getDirectMessages(new Paging(dms.sinceId))
      }
      tweets.reverse.foreach(t => process(twitter, pm, dms, t))
    } finally {
      pm.close
    }
  }

  def getDirectMessages(pm : PersistenceManager) = {
    val key: Key = KeyFactory.createKey(classOf[DirectMessages].getSimpleName(), DirectMessages.singletonKey);
    try {
      val dms = pm.getObjectById(classOf[DirectMessages], key)
      println("dm last id = " + dms.sinceId)
      dms
    }
    catch{
      case onf: JDOObjectNotFoundException => {
        println("did not find DirectMessages objects")
        new DirectMessages(key, 1)
      }
      case e:   Throwable => throw e
    }
  }

  implicit def dmToTwitterMessage(dm: DirectMessage) = TwitterDirectMessage(dm)

  def process(twitter: Twitter, pm : PersistenceManager, dms: DirectMessages, dm: DirectMessage) {
    println("got Direct Message : [" + dm.getId + "] " + dm.getText)
    val response = KCActor.act(twitter, pm, dm)
    try {
    	twitter.sendDirectMessage(dm.getSender.getScreenName, trunk(response.message))
    } catch {
	    case e: TwitterException if e.getMessage.contains("You cannot send messages to users who are not following you") =>
	      twitter.updateStatus("@" + dm.getSender.getScreenName + " " + trunk(response.message), dm.getId)
	    case other => other.printStackTrace
     }
    dms.sinceId = dm.getId 
    pm.makePersistent(dms)
  }

  private def trunk(str: String) = if(str.length > 140) (str.substring(0, 137) + "...") else str
}